package com.GLM.Viewer.Party;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.GLM.Constants.Constant;
import com.GLM.Entity.UserInfoDetailEntity;
import com.GLM.Tools.DB.DAO.UserInfoDAO;
import com.GLM.Tools.Utils.Image.AsynImageLoader;
import com.GLM.Tools.Utils.JSON.JSONResponse;
import com.GLM.Tools.Utils.JSON.JSONUtil;
import com.GLM.Tools.Utils.JSON.JSONResponse.Status;
import com.GLM.Viewer.R;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.NavUtils;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.TimePicker.OnTimeChangedListener;
import android.widget.TimePicker;

public class CreateNewPartyFriendViewActivity extends Activity {
	private final static int FRIENDLIST_LOADING = 111;
	private final static int FRIENDLIST_LONDED = 222;
	private ListView mFriendsList;
	private SimpleAdapter mFriendsAdapter;
	private List<Map<String, Object>> mFriendsItems = new ArrayList<Map<String, Object>>();
	private String[] friendsItemKeys = new String[] { "nickname", "location", "remark" };
	private int[] friendsItemIds = new int[] { R.id.newparty_friend_nickname, R.id.newparty_friend_loc, R.id.newparty_friend_remark };
	private Map<String, String> friendsPics = new HashMap<String, String>();
	private Set<String> friendsIdSet = new HashSet<String>();
	private Map<Integer, Integer> friendsMap = new HashMap<Integer, Integer>();
	private AsynImageLoader imageLoader = new AsynImageLoader();
	Button goBackButton;
	Button saveButton;
	Button notifyFriendButton;

	private String notifyTime;
	Calendar calendar;

	private int screenWidth;
	private int screenHeight;
	private String mMeetPlaceName;
	private String mMeetPlaceAddr;
	private String mMeetPlacePhone;
	private String mMeetTime;
	
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			Thread thread;
			switch (msg.what) {
			case FRIENDLIST_LOADING:
				thread = new Thread(new Runnable() {
					public void run() {
						
						initFriendsList();
						mFriendsAdapter = new SimpleAdapter(CreateNewPartyFriendViewActivity.this, mFriendsItems, R.layout.view_newparty_friend_listitem, friendsItemKeys, friendsItemIds);
						mHandler.sendEmptyMessage(FRIENDLIST_LONDED);
					}

				});
				thread.start();
				break;

			case FRIENDLIST_LONDED:
				if(mFriendsAdapter != null && mFriendsItems.size()>0){
					mFriendsList.setAdapter(mFriendsAdapter);
					bindItemClick();
				}else{
					Paint paint = new Paint();
					paint.setTextSize(20);
					paint.setAntiAlias(true);
					String str = getString(R.string.newparty_tips_nofriends);
					Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.glm_background);
					Canvas canvas = new Canvas(bitmap);
					canvas.drawText(str,screenWidth/2-str.length()*9 , screenHeight/2, paint);
					RelativeLayout layout = (RelativeLayout)findViewById(R.id.newparty_friends_layout);
					Drawable drawable = new BitmapDrawable(bitmap);
					layout.setBackgroundDrawable(drawable);
				}
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_newparty_friend);
		screenWidth = getWindowManager().getDefaultDisplay().getWidth();
		screenHeight = getWindowManager().getDefaultDisplay().getHeight();
		
		Intent intent = getIntent();
		mMeetPlaceName = intent.getStringExtra("MeetingPlaceName");
		mMeetPlaceAddr = intent.getStringExtra("MeetingPlaceAddr");
		mMeetPlacePhone = intent.getStringExtra("MeetingPlacePhone");
		mMeetTime = intent.getStringExtra("MeetingBegintTime");
		initButtons();
		mFriendsList = (ListView) findViewById(R.id.newparty_friendlist);
		mHandler.sendEmptyMessage(FRIENDLIST_LOADING);
	}

	public void initButtons() {
		goBackButton = (Button) findViewById(R.id.goback_newparty_friend_Button);
		saveButton = (Button) findViewById(R.id.newparty_friend_save_button);
		notifyFriendButton = (Button) findViewById(R.id.newparty_notify_button);
		goBackButton.setOnClickListener(onClickListeners);
		saveButton.setOnClickListener(onClickListeners);
		notifyFriendButton.setOnClickListener(onClickListeners);
	}

	OnClickListener onClickListeners = new OnClickListener() {

		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.goback_newparty_friend_Button:
				NavUtils.navigateUpTo(CreateNewPartyFriendViewActivity.this, new Intent(CreateNewPartyFriendViewActivity.this, CreateNewPartyViewActivity.class));
				break;
			case R.id.newparty_notify_button:
				if(mMeetTime == null){
					initShowDialog();
				}else{
					Intent toIntent = new Intent(CreateNewPartyFriendViewActivity.this,CreateNewPartyContactViewActivity.class);
					toIntent.putExtra("MeetingPlaceName", mMeetPlaceName);
					toIntent.putExtra("MeetingPlaceAddr", mMeetPlaceAddr);
					toIntent.putExtra("MeetingPlacePhone", mMeetPlacePhone);
					toIntent.putExtra("MeetingTime", mMeetTime);
				}
				break;
			case R.id.newparty_friend_save_button:
				doSaveBtnClick();
				break;

			}
		}
	};

	public OnScrollListener scrollListener = new OnScrollListener() {

		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub

		}

		public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
			// TODO Auto-generated method stub
			LoadFriendPic();
		}
	};

	public void bindItemClick() {

		mFriendsList.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
				// TODO Auto-generated method stub
				Log.v("clicked", "position ->" + position + " userid -> " + friendsMap.get(position));
				ImageView chooseView = (ImageView) v.findViewById(R.id.newparty_friend_choose_imageview);
				if (chooseView.getVisibility() == View.VISIBLE) {
					chooseView.setVisibility(View.INVISIBLE);
					friendsIdSet.remove(friendsMap.get(position));
				} else {
					chooseView.setVisibility(View.VISIBLE);
					friendsIdSet.add(String.valueOf(friendsMap.get(position)));
				}

			}
		});

		mFriendsList.setOnScrollListener(scrollListener);
	}

	public void LoadFriendPic() {
		int count = mFriendsList.getChildCount();
		for (int i = 0; i < count; i++) {
			View view = mFriendsList.getChildAt(i);
			ImageView imageView = (ImageView) view.findViewById(R.id.newparty_friend_avatar);
			String key = String.valueOf(i);
			String picurl = friendsPics.get(key);
			if (picurl != null && picurl != "") {
				imageLoader.showImageAsyn(imageView, Constant.URL_USER_MIDDLE + picurl, R.drawable.glm_white);

			}
		}
	}

	public void initFriendsList() {
		JSONObject jsonData = new JSONObject();
		JSONResponse jsonResponse = null;
		try {
			jsonData.put(Constant.PARAM_USERID_ONE, UserInfoDAO.getUserInfo(CreateNewPartyFriendViewActivity.this).getUserId());
			jsonResponse = JSONUtil.postRequest(Constant.REQ_WAY_GETFRIENDLIST, jsonData);
			if (jsonResponse.getStatus() != Status.ERR) {
				int status = -1;
				JSONObject data = jsonResponse.getData();
				status = data.getInt(Constant.RESP_STATUS);
				if (status == Constant.RESP_STATUS_SUCCESS) {
					JSONArray jsonArray = data.getJSONArray(Constant.RESP_CIRCLE_MYFRIENDS);

					initFriendItemFromJson(jsonArray);
				}

			}
		} catch (Exception e) {
			// TODO: handle exception

		}
	}

	public void initFriendItemFromJson(JSONArray jsonArray) throws JsonSyntaxException, JSONException {
		Gson gson = new Gson();
		for (int i = 0; i < jsonArray.length(); i++) {
			UserInfoDetailEntity entity = gson.fromJson(jsonArray.getJSONObject(i).toString(), UserInfoDetailEntity.class);
			Map<String, Object> item = new HashMap<String, Object>();
			item.put("nickname", entity.getUd_nickname());
			item.put("location", entity.getLoc_name());
			item.put("remark", entity.getUd_relname());
			
			mFriendsItems.add(item);
			Log.d("Loc_id>", entity.getUser_avatar() + "");
			friendsPics.put(String.valueOf(i), entity.getUser_avatar());

			friendsMap.put(i, entity.getUser_id());
		}
	}

	public void doSaveBtnClick() {

		Intent intent = new Intent(CreateNewPartyFriendViewActivity.this, CreateNewPartyViewActivity.class);
		int count = friendsIdSet.size();
		Log.d("count", count + "");
		if (count > 0) {
			int[] Ids = new int[count];
			int i = 0;
			Iterator<String> iterator = friendsIdSet.iterator();
			while(iterator.hasNext()){
				Ids[i++] = Integer.valueOf(iterator.next());
			}
			intent.putExtra("chooseFriends", Ids);
		} else
			intent.putExtra("chooseFriends", "");
		setResult(RESULT_OK, intent);
		finish();
	}

	public void initShowDialog() {
		calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH);
		int day = calendar.get(Calendar.DAY_OF_MONTH);

		AlertDialog.Builder builder = new AlertDialog.Builder(CreateNewPartyFriendViewActivity.this);
		builder.setTitle(getString(R.string.newparty_tips_notify_time));
		View timeView = LayoutInflater.from(CreateNewPartyFriendViewActivity.this).inflate(R.layout.view_newparty_notify_dialog, null);
		builder.setView(timeView);
		DatePicker dp = (DatePicker) timeView.findViewById(R.id.newparty_datepicker);
		TimePicker tp = (TimePicker) timeView.findViewById(R.id.newparty_timepicker);
		tp.setIs24HourView(true);
		dp.init(year, month, day, new OnDateChangedListener() {

			public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
				// TODO Auto-generated method stub
				calendar.set(Calendar.YEAR, year);
				calendar.set(Calendar.MONTH, monthOfYear);
				calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			}
		});
		tp.setOnTimeChangedListener(new OnTimeChangedListener() {

			public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
				// TODO Auto-generated method stub
				calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
				calendar.set(Calendar.MINUTE, minute);
			}
		});

		builder.setNegativeButton(getString(R.string.newparty_time_cancel), new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				
			}
		});
		builder.setPositiveButton(getString(R.string.newparty_time_save), new DialogInterface.OnClickListener() {

			@SuppressWarnings("static-access")
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				DateFormat dformat = new DateFormat();
				notifyTime = (String) dformat.format("yyyy-MM-dd hh:mm", calendar);
				Intent tocontact = new Intent(CreateNewPartyFriendViewActivity.this, CreateNewPartyContactViewActivity.class);
				tocontact.putExtra("MeetingPlaceName", mMeetPlaceName);
				tocontact.putExtra("MeetingPlaceAddr", mMeetPlaceAddr);
				tocontact.putExtra("MeetingPlacePhone", mMeetPlacePhone);
				tocontact.putExtra("MeetingTime", notifyTime);
				startActivity(tocontact);
				
			}
		});
		builder.show();
	}

}
